package com.ques.dao;

import com.mongodb.client.result.DeleteResult;
import com.ques.entity.QueryParam;
import com.ques.pojo.QuestionAnswer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author zq  2020-02-08
 */
@Repository
public class AnswerDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    public boolean inserAnswer(String questionId, QuestionAnswer questionAnswer) {
        // 一问卷id 进行唯一确实定 表
        QuestionAnswer question = mongoTemplate.insert(questionAnswer, questionId);
        return question != null;
    }



    public List<QuestionAnswer> selectAllAnswerPage(QueryParam queryParam) {
        Query query = new Query();
        long total = mongoTemplate.count(query, queryParam.getId());
        queryParam.setTotal( total );
        // 重第0 也开始算的
        // 计算数量够不够
        if ( (queryParam.getCurrentPage()+1) * queryParam.getPageSize() > total) {
            queryParam.setCurrentPage( (int)total / queryParam.getPageSize() );
        }
        Pageable pageable = PageRequest.of(queryParam.getCurrentPage(), queryParam.getPageSize() );
        List<QuestionAnswer> questionAnswers = mongoTemplate.find(query.with(pageable), QuestionAnswer.class, queryParam.getId());

        return questionAnswers;
    }

    public List<QuestionAnswer> selectAllAnswer(String questionId) {
        List<QuestionAnswer> answers = mongoTemplate.findAll(QuestionAnswer.class, questionId);
        return answers;
    }


    public long deleteAnswer(String quesId, List<String> answerId) {
        long count = 0 ;
        for (String id : answerId) {
            Query query = Query.query(Criteria.where("_id").is(id ));
            DeleteResult remove = mongoTemplate.remove(query, quesId);
            count += remove.getDeletedCount();
        }
        return  count ;
    }
}
